﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;

namespace YouWei.Api.Filters
{
    /// <summary>
    /// CORS
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class ActionCORS : ActionFilterAttribute
    {
        /// <summary>
        /// 跨域请求
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {

            if (actionExecutedContext.Response != null && !actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<DisableCORS>().Any())
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
                //响应头添加Access-Control-Allow-Origin *是全部允许，如果允许某个域名，则直接写域名 
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
               // actionExecutedContext.Response.Headers.Add("Access-Control-Max-Age", "-1");
            }
            base.OnActionExecuted(actionExecutedContext);
        }
    }

    /// <summary>
    /// CORS
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class DisableCORS : ActionFilterAttribute
    {
        /// <summary>
        /// 跨域请求
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    }

}